package com.lxy.cxcyxmmsbackend.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lxy.cxcyxmmsbackend.sys.entity.CxcyXm;
import com.lxy.cxcyxmmsbackend.sys.entity.KeyValue;
import com.lxy.cxcyxmmsbackend.sys.entity.QxglRole;
import com.lxy.cxcyxmmsbackend.sys.entity.QxglUser;
import com.lxy.cxcyxmmsbackend.sys.exceptionHandle.exce.NormalException;
import com.lxy.cxcyxmmsbackend.sys.mapper.*;
import com.lxy.cxcyxmmsbackend.sys.req.LoginReq;
import com.lxy.cxcyxmmsbackend.sys.req.PageReq;
import com.lxy.cxcyxmmsbackend.sys.res.PageRes;
import com.lxy.cxcyxmmsbackend.sys.res.Result;
import com.lxy.cxcyxmmsbackend.sys.service.QxglUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxy.cxcyxmmsbackend.sys.utils.JwtUtil;
import com.lxy.cxcyxmmsbackend.sys.utils.MD5Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 刘新颖
 * @since 2024-01-07
 */
@Service
public class QxglUserServiceImpl extends ServiceImpl<QxglUserMapper, QxglUser> implements QxglUserService {

    @Resource
    QxglUserMapper qxglUserMapper;
    @Resource
    QxglRoleMapper qxglRoleMapper;
    @Resource
    PermissionMapper permissionMapper;
    @Resource
    QxglCdMapper qxglCdMapper;
    @Resource
    QxglDzMapper qxglDzMapper;
    @Resource
    CommonMapper commonMapper;

    @Resource
    PageRes pageRes;

    @Resource
    CxcyXmMapper cxcyXmMapper;

    @Resource
    KeyValueMapper keyValueMapper;


    @Override
    @Transactional
    public Result login(LoginReq loginReq) {
//        QxglUser user = qxglUserMapper.selectUserById(loginReq.getUserCode());
        QueryWrapper<QxglUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(QxglUser::getUserCode,loginReq.getUserCode());
        QxglUser user = qxglUserMapper.selectOne(queryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        if (user == null) {
            throw new NormalException("无该用户！！请重新输入！");
        }
        if (user.getStatus().equals("0")){
            throw new NormalException("请等待管理员审批后进行登录！");
        }
        if (user.getStatus().equals("-1")){
            throw new NormalException("该账号已被停用，请联系管理员重新启用！");
        }
        boolean validpassword = false;
        try {
//            validpassword = MD5Util.validpassword(loginReq.getPassword(), user.getUserMm());
            validpassword = loginReq.getPassword().equals(user.getUserMm());
        } catch (Exception e) {
            e.printStackTrace();
        }
        String token = "";
        if (validpassword) {
            user.setLoginTime(new Date(System.currentTimeMillis()));
            qxglUserMapper.updateUser(user);
            token = JwtUtil.getToken(String.valueOf(user.getUserBh()));
            //获取角色 角色下拥有的菜单和动作 id
            QxglRole role = qxglRoleMapper.selectRoleByUser_id(user.getUserBh());
            List<String> apis = null;
            if ("R2001".equals(role.getRoleBh())){
                apis =  qxglDzMapper.selectAllApi();
            }else {
                apis = qxglDzMapper.selectApiByUid(user.getUserBh());
            }

            List<String> menu_ids;
            if ("R2001".equals(role.getRoleBh())) {
                menu_ids = qxglCdMapper.selectAllMid();
            } else {
                menu_ids = permissionMapper.selectMIdByRId(role.getRoleBh());
            }

            ArrayList<String> permission_ids = new ArrayList<>(menu_ids);
            map.put("menu_ids", permission_ids);
            map.put("dzJks", apis);
            map.put("userName", user.getUserMc());
            map.put("user", user);
            QueryWrapper<CxcyXm> queryWrapper1 = new QueryWrapper<>();
            String xmBh = user.getXmBh();
            if (xmBh !=null && !"".equals(xmBh)){
                queryWrapper1.lambda().eq(CxcyXm::getXmBh,xmBh);
                CxcyXm cxcyXm = cxcyXmMapper.selectOne(queryWrapper1);
                map.put("cxcyXm", cxcyXm);
            }else {
                map.put("cxcyXm", null);
            }

            map.put("token", token);


        } else {
            throw new NormalException("密码错误，请重新输入！");
        }
        return Result.success("登录成功！", map);
    }

    @Override
    @Transactional
    public Result selectIds(String userBh) {
        String roleBh = qxglRoleMapper.selectRoleByUser_id(userBh).getRoleBh();
        HashMap<String, Object> map = new HashMap<>();
        List<String> apis = qxglDzMapper.selectApiByUid(userBh);
        map.put("apis", apis);
        ArrayList<String> permission_ids = new ArrayList<>();
        List<String> menu_ids;
        List<String> action_nos;
        if ("R2001".equals(roleBh)) {
            menu_ids = qxglCdMapper.selectAllMid();
            action_nos = qxglDzMapper.selectAllAid();
        } else {
            menu_ids = permissionMapper.selectMIdByRId(roleBh);
            action_nos = permissionMapper.selectAIdByRId(roleBh);
        }

        permission_ids.addAll(menu_ids);
        permission_ids.addAll(action_nos);
        map.put("permission_ids", permission_ids);
        return Result.success("查询api和权限成功",map);
    }

    @Override
    @Transactional
    public Result selectUserByUid(String userBh) {
        QxglUser user = qxglUserMapper.selectUserById(userBh);

        if (user == null) {
            throw new NormalException("未查询到该用户");
        }
        return Result.success("查询用户成功", user);
    }

    @Override
    @Transactional
    public Result selectUserPage(PageReq pageReq) {
        List<QxglUser> users = qxglUserMapper.selectUserPage(
                (pageReq.getCurrentPage() - 1) * pageReq.getPageSize(),
                pageReq.getPageSize(),
                pageReq.getKeyWord().get("userMc"),
                pageReq.getKeyWord().get("userSjh"),
                pageReq.getKeyWord().get("roleBh"),
                pageReq.getKeyWord().get("userXy"),
                pageReq.getKeyWord().get("status"));
        for (QxglUser user : users) {
//            try {
//                user.setUserMm(MD5Util.getEncryptedPwd(user.getUserMm()));
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
        }
        if (users == null || users.size() == 0) {
            throw new NormalException("分页查询用户失败");
        }
        int size = qxglUserMapper.countUser(pageReq.getKeyWord());
        int totalSize = (int) Math.ceil((double) size / pageReq.getPageSize());

        pageRes.setCurrentPage(pageReq.getCurrentPage());
        HashMap<String, Object> map = new HashMap<>();
        map.put("keyWord",pageReq.getKeyWord());
        pageRes.setKeyWord(map);
        pageRes.setPageSize(pageReq.getPageSize());
        pageRes.setObjects(users);
        pageRes.setSize(size);
        pageRes.setTotalSize(totalSize);

        return Result.success("分页查询用户成功", pageRes);
    }

    @Override
    @Transactional
    public Result insertUser(QxglUser user) {

        QueryWrapper<QxglUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(QxglUser::getUserCode,user.getUserCode());
        List<QxglUser> qxglUsers = qxglUserMapper.selectList(wrapper);
        if (qxglUsers.size()>0){
            throw new NormalException("该用户已经存在！");
        }

        String userBh = commonMapper.getNewBhUser();
        user.setUserBh(userBh);
        user.setCreateTime(new Date(System.currentTimeMillis()));
        try {
//            String encryptedPwd = MD5Util.getEncryptedPwd(user.getUserMm());
//            user.setUserMm(user.getUserMm());
            user.setUserMm("123456");
        } catch (Exception e) {
            e.printStackTrace();
        }
        QueryWrapper<KeyValue> queryWrapper ;
        if (!"".equals(user.getUserXy()) && user.getUserXy() != null){
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(KeyValue::getKeycode,"xy");
            queryWrapper.lambda().eq(KeyValue::getKeyvalue,user.getUserXy());
            KeyValue keyValue = keyValueMapper.selectOne(queryWrapper);
            user.setUserXymc(keyValue.getKeyname());
        }

        if (!"".equals(user.getUserBm()) && user.getUserBm() != null){
            queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(KeyValue::getKeycode,"bm");
            queryWrapper.lambda().eq(KeyValue::getKeyvalue,user.getUserBm());
            KeyValue keyValue = keyValueMapper.selectOne(queryWrapper);
            user.setUserBmmc(keyValue.getKeyname());
        }

        QxglRole qxglRole = qxglRoleMapper.selectById(user.getRoleBh());
        user.setRoleMc(qxglRole.getRoleMc());
        user.setStatus("0");
        int i = qxglUserMapper.insert(user);
        if (i != 1) {
            throw new NormalException("新增用户失败");
        }
        return Result.success("新增用户成功", user);
    }

    @Override
    @Transactional
    public Result updateUser(QxglUser user) {
        int i = qxglUserMapper.updateUser(user);
        if (i != 1) {
            throw new NormalException("修改用户失败");
        }
        return Result.success("修改用户成功", user);
    }

    @Override
    @Transactional
    public Result deleteUser(String userBh) {
        int i = qxglUserMapper.deleteUser(userBh);
        if (i != 1) {
            throw new NormalException("删除用户失败");
        }
        return Result.success("删除用户成功", userBh);
    }
}
